package com.wayne.leetcode.problems;

public class Solution556 {
  public static int nextGreaterElement(int n) {
    char[] nums = Integer.toString(n).toCharArray();
    int len = nums.length;
    if (len == 1) return -1;
    int i = len - 2;
    while (i >= 0 && nums[i] >= nums[i + 1]) {
      i--;
    }
    if (i < 0) return -1;
    int j = len - 1;
    while (j>i && nums[i]>=nums[j]) {
      j--;
    }
    swap(nums, i, j);
    reverse(nums, i + 1);
    long ans = Long.parseLong(new String(nums));
    return ans > Integer.MAX_VALUE ? -1 : (int) ans;
  }

  public static void reverse(char[] nums, int begin) {
    int i = begin, j = nums.length - 1;
    while (i < j) {
      swap(nums, i, j);
      i++;
      j--;
    }
  }

  public static void swap(char[] nums, int i, int j) {
    char temp = nums[i];
    nums[i] = nums[j];
    nums[j] = temp;
  }

  public static void main(String[] args) {
    System.out.println(nextGreaterElement(2147483476));
  }
}